/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.wxs.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * <p>Project: ssm0 - ApplicationContextConfig
 * <p>Description : 相当于 resources/applicationContext.xml spring IoC 框架核心配置文件
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 15
 */
@Configuration
@MapperScan("cn.webrx.wxs.mapper")
//加载properties
@PropertySource("classpath:db.properties")
public class ApplicationContextConfig {
    //@Value("#{systemProperties['os.name']}")
    //@Value("#{ T(java.lang.Math).random() * 100.0 }")
    @Value("${db.url}")
    private String url;
    @Value("${db.username}")
    private String username;
    @Value("${db.driver}")
    private String driver;
    @Value("${db.filters}")
    private String filters;
    @Value("${db.password}")
    private String password;
    @Value("${db.publicKey}")
    private String publickey;

    @Bean("ds")
    public DataSource druidDataSource(@Value("${db.driver}") String driver, @Value("${db.password}") String password, @Value("${db.publicKey}") String publickey, @Value("${db.filters}") String filters, @Value("${db.url}") String url, @Value("${db.username}") String uname) throws SQLException {
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(uname);
        ds.setPassword(password);
        ds.setFilters(filters);
        ds.setConnectionProperties("config.decrypt=true;config.decrypt.key=" + publickey);
        ds.setDriverClassName(driver);
        return ds;
    }

    /**
     * 配置事务管理器
     */
    //@Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("ds") DataSource ds) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(ds);
        return dataSourceTransactionManager;
    }

    /**
     * 配置分页插件(mybatis拦截器插件)
     *
     * @return
     */
    public PageInterceptor pageInterceptor() {
        var pi = new PageInterceptor();
        var prop = new Properties();
        prop.setProperty("reasonable", "true");
        pi.setProperties(prop);
        return pi;
    }

    /**
     * 注册SqlSessionFactory
     *
     * @param ds
     * @return
     */
    @Bean("sf")
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Qualifier("ds") DataSource ds) {
        SqlSessionFactoryBean sf = new SqlSessionFactoryBean();
        sf.setDataSource(ds);
        //mybatis 分页插件注册
        sf.setPlugins(pageInterceptor());
        sf.setTypeAliasesPackage("cn.webrx.wxs.entity");
        sf.setMapperLocations(resolveMapperLocations());
        return sf;
    }

    public Resource[] resolveMapperLocations() {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<String> mapperLocations = new ArrayList<>();
        mapperLocations.add("classpath:cn/webrx/wxs/mapper/*Mapper.xml");
        List<Resource> resources = new ArrayList<>();
        for (String mapperLocation : mapperLocations) {
            try {
                Resource[] mappers = resourceResolver.getResources(mapperLocation);
                resources.addAll(Arrays.asList(mappers));
            } catch (IOException ignored) {
            }
        }
        return resources.toArray(new Resource[0]);
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("cn.webrx.wxs.mapper");
        msc.setSqlSessionFactoryBeanName("sf");
        return msc;
    }

}
